#include <48func.h>
typedef struct shareRes_s {
    int flag; //决定了B可不可以执行
    pthread_mutex_t mutex;
    pthread_cond_t cond;
} shareRes_t;
void *threadFunc(void *arg){
    shareRes_t *pshareRes = (shareRes_t *)arg;
    // 判断B能否执行
    pthread_mutex_lock(&pshareRes->mutex);
    if(pshareRes->flag == 0){
        //B不能执行
        //上半部 检查加锁 加入唤醒队列 解锁并陷入等待
        //下半部 醒来 加锁 继续带锁运行
        pthread_cond_wait(&pshareRes->cond,&pshareRes->mutex);
    }
    pthread_mutex_unlock(&pshareRes->mutex);
    printf("B is done!\n");
    pthread_exit(NULL);
}
int main()
{
    shareRes_t shareRes;
    shareRes.flag = 0;
    pthread_mutex_init(&shareRes.mutex,NULL);//初始化锁
    pthread_cond_init(&shareRes.cond,NULL);//初始化条件变量
    pthread_t tid;
    pthread_create(&tid,NULL,threadFunc,&shareRes);
    // 先执行A
    printf("A is begin!\n");
    printf("A is end!\n");
    // 修改flag
    pthread_mutex_lock(&shareRes.mutex);
    shareRes.flag = 1; // B可以执行了
    pthread_cond_signal(&shareRes.cond);
    pthread_mutex_unlock(&shareRes.mutex);
    pthread_join(tid,NULL);
    return 0;
}

